// @ts-ignore
import { PageType } from "@/interface/index";

/**
 * 获取默认的路径
 * @param list
 */
export function getDefaultPath(list: Array<PageType>) {
  function getPage(list: Array<PageType>) {
    if (list && list[0] && list[0].children && list[0].children.length > 0) {
      return getPage(list[0].children);
    } else {
      return list[0].path;
    }
  }
  return getPage(list);
}

/**
 * 递归提升路由
 * @param list
 * @param basePath
 * @returns
 */
export function recursionLiftRouter(list: Array<PageType>) {
  if (!list || list.length <= 0) {
    return [];
  }
  for (let index = 0; index < list.length; index++) {
    list[index].children = recursionLiftRouter(list[index].children || []);
    list[index] = neatenRouter(list[index]);
  }
  return list;
}

/**
 * 递归拼接路径
 * @param list
 * @param basePath
 * @returns
 */
export function recursionNeatenRouter(list: Array<PageType>, basePath: string) {
  if (!list || list.length == 0) {
    return [];
  }
  for (let index = 0; index < list.length; index++) {
    let element = list[index];
    element.path = resolve(element.path, basePath);
    element.children = recursionNeatenRouter(
      element.children || [],
      element.path
    );
  }
  return list;
}

/**
 * (提升路由) 将只有一个子元素的层级向上提升
 * @param pages
 * @param basePath
 * @returns
 */
function neatenRouter(pages: PageType): PageType {
  if (pages.children && pages.children.length != 0) {
    if (pages.children.length == 1) {
      let path = resolve(pages.children[0].path, pages.path);
      pages = pages.children[0];
      pages.path = path;
    }
  }
  return pages;
}

/**
 * 拼接路径
 * @param path
 * @param basePath
 * @returns
 */
function resolve(path: string, basePath: string) {
  if (!path) {
    return basePath;
  }
  if (isExternal(path)) {
    return path;
  }
  if (isExternal(basePath)) {
    return basePath;
  }
  let regex = /\/\//g; // 使用正则表达式并设置全局标志g
  let newStr = (basePath + path).replace(regex, "/"); // 替换所有的 "//" 为 "/"
  return newStr;
}

/**
 * 是否外部链接
 */
function isExternal(path: string) {
  return /^(http?:|mailto:|tel:)/.test(path);
}
